package cn.tedu.front.search.service.impl;


import cn.tedu.front.search.dao.cache.IDistrictCacheRepository;
import cn.tedu.front.search.dao.persist.repository.IDistrictRepository;
import cn.tedu.front.search.pojo.po.DistrictSimplePO;
import cn.tedu.front.search.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    @Override
    public List<DistrictSimplePO> listByParent(Long parentId) {
        // return districtRepository.listByParent(parentId);
        List<DistrictSimplePO> cacheList = districtCacheRepository.listByParent(parentId);
//        if (cacheList.size() == 0) {
//            List<DistrictSimpleVO> dbList = districtRepository.listByParent(parentId);
//            districtCacheRepository.saveList(parentId, dbList);
//            return dbList;
//        }
        return cacheList;
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();

        Long parentId = 0L;
        List<DistrictSimplePO> districtList = districtRepository.listByParent(parentId);
        districtCacheRepository.saveList(parentId, districtList);
        callRecursion(districtList);
    }

    private void callRecursion(List<DistrictSimplePO> districtList) {
        for (DistrictSimplePO district : districtList) {
            districtCacheRepository.save(district);

            Long id = district.getId();
            List<DistrictSimplePO> subList = districtRepository.listByParent(id);
            if (subList.size() > 0) {
                districtCacheRepository.saveList(id, subList);
                callRecursion(subList);
            }
        }
    }


}
